package com.mukefile.dao.impl;

import com.mukefile.dao.ShareFileDao;
import com.mukefile.pojo.ShareFile;
import org.hibernate.Session;
import org.hibernate.query.NativeQuery;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Author: kenewstar
 * @Description:
 * @Date:Created in 2020/5/7
 */
@Repository("shareFileDao")
public class ShareFileDaoImpl implements ShareFileDao {

    @Autowired
    private HibernateTemplate hibernateTemplate;
    @Override
    public List<ShareFile> selectAllShareFile() {
        //获取Session
        Session session = this.hibernateTemplate.getSessionFactory().getCurrentSession();
        //Sql
        String sql = "select * from sharefile";
        //创建查询
        Query query = session.createSQLQuery(sql).addEntity(ShareFile.class);
        //返回list
        return query.list();
    }

    @Override
    public int deleteFile(Integer fid) {
        ShareFile shareFile = new ShareFile();
        shareFile.setId(fid);
        try {
            this.hibernateTemplate.delete(shareFile);
        }catch (Exception e){
            return 0;
        }
        return 1;
    }

    @Override
    public int fileUpload(ShareFile shareFile) {
        ShareFile shareFile1 = this.selectShareFile(shareFile.getFileName());
        if (shareFile1!=null){
            //文件不为空
            return 0;
        }
        try {
            this.hibernateTemplate.save(shareFile);
        }catch (Exception e){
            return 0;
        }
        return 1;
    }

    public ShareFile selectShareFile(String fileName){
        Session session = this.hibernateTemplate.getSessionFactory().getCurrentSession();
        String sql = "select * from sharefile where fileName=?";
        Query query = session.createSQLQuery(sql).addEntity(ShareFile.class).setParameter(1, fileName);
        if (query.list().isEmpty()){
            return null;
        }
        return (ShareFile) query.list().get(0);
    }


}
